/*************************************************************************
 *  Copyright © 2023-2030 FXB CO.,LTD. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：CustomBuildProcess
 *  文件：SoftPropertyOutput.cs
 *  作者：Administrator
 *  日期：2025/6/14 22:25:27
 *  功能：Nothing
*************************************************************************/

using System;
using System.Xml;
using UnityEditor;
using UnityEngine;

namespace CustomBuildProcess.Editor
{
    public class SoftPropertyOutput
    {
        public static void WriteSoftPropertyToBuildDirectory(string targetPath, BuildInfo lastBuildInfo, BuildConfigItem buildConfigItem)
        {
            try
            {
                // 创建 XML 文档
                XmlDocument xmlDoc = new XmlDocument();

                // 添加 XML 声明
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                xmlDoc.AppendChild(xmlDeclaration);


                // 创建根节点
                XmlElement root = xmlDoc.CreateElement("SoftwareInfo");
                xmlDoc.AppendChild(root);

                // 添加子节点
                AddXmlElement(xmlDoc, root, "BuildTime", $"{lastBuildInfo.buildTime}");
                AddXmlElement(xmlDoc, root, "Platform", $"{buildConfigItem.GetPlatform(lastBuildInfo.platform)}");
                AddXmlElement(xmlDoc, root, "AppID", $"{lastBuildInfo.appID}");
                AddXmlElement(xmlDoc, root, "Feature", $"{buildConfigItem.GetFeature(lastBuildInfo.feature)}");
                AddXmlElement(xmlDoc, root, "Model", $"{buildConfigItem.GetModel(lastBuildInfo.model)}");
                AddXmlElement(xmlDoc, root, "Language", $"{buildConfigItem.GetLanguage(lastBuildInfo.language)}");
                AddXmlElement(xmlDoc, root, "Type", $"{buildConfigItem.GetType(lastBuildInfo.type)}");
                AddXmlElement(xmlDoc, root, "CompanyName", $"{lastBuildInfo.companyName}");
                AddXmlElement(xmlDoc, root, "ProductName", $"{lastBuildInfo.productName}");
                AddXmlElement(xmlDoc, root, "Version", $"V{lastBuildInfo.version}");

                // 保存到文件
                xmlDoc.Save(targetPath);

                Debug.Log($"Successfully written software properties to {targetPath}");

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to written software properties: {e.Message}");
            }
        }

        private static void AddXmlElement(XmlDocument xmlDoc, XmlElement parent, string elementName, string value)
        {
            XmlElement element = xmlDoc.CreateElement(elementName);
            element.InnerText = value;
            parent.AppendChild(element);
        }
    }
}